using System.Collections.Generic;
using System.Data;
using MySql.Data.MySqlClient;
using RuiXinCoffee.Utils;
using System.IO;
using System;
using System.Windows.Forms;

namespace RuiXinCoffee.BLL
{
    public class CarouselImageService
    {
        //获取所有轮播图片按照顺序
        public List<string> GetAllImages()
        {
            try
            {
                string sql = "SELECT ImageUrl FROM CarouselImage ORDER BY DisplayOrder, Id";
                DataTable dt = DBhelp.ExecuteDataTable(sql);
                var list = new List<string>();
                foreach (DataRow row in dt.Rows)
                {
                    string imageUrl = row["ImageUrl"].ToString();
                    if (!string.IsNullOrEmpty(imageUrl))
                    {
                        if (imageUrl.StartsWith("Image/"))
                        {
                            imageUrl = "Images/" + imageUrl.Substring(6);
                        }
                        
                        if (!imageUrl.Contains("/Carousel/"))
                        {
                            try
                            {
                                string baseDir = AppDomain.CurrentDomain.BaseDirectory;
                                string projectDir = baseDir;
                                if (baseDir.Contains("\\bin\\"))
                                {
                                    projectDir = baseDir.Substring(0, baseDir.IndexOf("\\bin\\"));
                                }
                                
                                string oldPath = Path.Combine(projectDir, imageUrl);
                                if (File.Exists(oldPath))
                                {
                                    string newPath = ImageHelper.SaveCarouselImage(oldPath);
                                    UpdateImagePath(imageUrl, newPath);
                                    imageUrl = newPath;
                                }
                            }
                            catch
                            {
                                // 忽略错误，继续使用旧路径
                            }
                        }
                        
                        list.Add(imageUrl);
                    }
                }
                return list;
            }
            catch (Exception ex)
            {
                throw new BusinessException($"获取轮播图片失败: {ex.Message}", ex);
            }
        }

        //更新图片路径
        private void UpdateImagePath(string oldPath, string newPath)
        {
            try
            {
                string sql = "UPDATE CarouselImage SET ImageUrl = @NewPath WHERE ImageUrl = @OldPath";
                var parameters = new MySqlParameter[]
                {
                    new MySqlParameter("@NewPath", newPath),
                    new MySqlParameter("@OldPath", oldPath)
                };
                DBhelp.ExecuteNonQuery(sql, parameters);
            }
            catch (Exception ex)
            {
                throw new DatabaseException($"更新图片路径失败: {ex.Message}", ex);
            }
        }

        //添加图片
        public void AddImage(string imageUrl, int displayOrder = 0)
        {
            try
            {
                if (!string.IsNullOrEmpty(imageUrl) && !imageUrl.Contains("/Carousel/"))
                {
                    string baseDir = AppDomain.CurrentDomain.BaseDirectory;
                    string projectDir = baseDir;
                    if (baseDir.Contains("\\bin\\"))
                    {
                        projectDir = baseDir.Substring(0, baseDir.IndexOf("\\bin\\"));
                    }
                    
                    string sourcePath;
                    
                    if (imageUrl.StartsWith("Images/") || imageUrl.StartsWith("Image/"))
                    {
                        sourcePath = Path.Combine(projectDir, imageUrl);
                    }
                    else
                    {
                        sourcePath = imageUrl;
                    }
                    
                    if (File.Exists(sourcePath))
                    {
                        imageUrl = ImageHelper.SaveCarouselImage(sourcePath);
                    }
                }
                
                string sql = "INSERT INTO CarouselImage (ImageUrl, DisplayOrder) VALUES (@ImageUrl, @DisplayOrder)";
                var parameters = new MySqlParameter[]
                {
                    new MySqlParameter("@ImageUrl", imageUrl),
                    new MySqlParameter("@DisplayOrder", displayOrder)
                };
                DBhelp.ExecuteNonQuery(sql, parameters);
            }
            catch (Exception ex)
            {
                throw new BusinessException($"添加轮播图片失败: {ex.Message}", ex);
            }
        }

        //删除图片
        public void DeleteImage(string imageUrl)
        {
            try
            {
                string sql = "DELETE FROM CarouselImage WHERE ImageUrl = @ImageUrl";
                var parameters = new MySqlParameter[]
                {
                    new MySqlParameter("@ImageUrl", imageUrl)
                };
                DBhelp.ExecuteNonQuery(sql, parameters);
                
                try
                {
                    string baseDir = AppDomain.CurrentDomain.BaseDirectory;
                    string projectDir = baseDir;
                    if (baseDir.Contains("\\bin\\"))
                    {
                        projectDir = baseDir.Substring(0, baseDir.IndexOf("\\bin\\"));
                    }
                    
                    string fullPath = Path.Combine(projectDir, imageUrl);
                    if (File.Exists(fullPath))
                    {
                        File.Delete(fullPath);
                    }
                }
                catch
                {
                    // 忽略删除文件失败的错误
                }
            }
            catch (Exception ex)
            {
                throw new BusinessException($"删除轮播图片失败: {ex.Message}", ex);
            }
        }
    }
}